<template>
  <div class="ffu_total">
    <px-radio-group v-model="chartType" class="switch-button" size="small" @change="changeChartType">
      <px-radio-button label="桑基图" />
      <px-radio-button label="流程图" />
    </px-radio-group>
    <div class="back-wrap">
      <px-button v-show="isShowDetail" type="primary" icon="ArrowLeft" size="small" @click="backClick">返回</px-button>
    </div>
    <div v-show="chartType === '桑基图' && !isShowDetail" class="sankey-chart-dom" @wheel.prevent="onWheel">
      <div ref="sankeyChartDomRef" class="sankey-chart" :style="{ scale: wheelScale }" />
    </div>

    <!-- <iframe
      v-show="chartType === '流程图' && !isShowDetail"
      id="preivewFrame"
      class="iframe-con"
      scrolling="no"
      :src="`${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=energy/${templateName}&startTime=${queryParams.startTime}&endTime=${queryParams.endTime}&factory=${queryParams.factory}&op=view&sysId=${sysId}`"
      frameborder="0"
    /> -->
    <iframe
      v-if="chartType === '流程图' || isShowDetail"
      id="preivewFrame"
      class="iframe-con"
      scrolling="no"
      :src="`${VITE_FANRUAN_BASE_URL}/webroot/decision/view/form?viewlet=energy/${templateName}&startTime=${queryParams.startTime}&endTime=${queryParams.endTime}&factory=${queryParams.factory}&sysId=${sysId}`"
      frameborder="0"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from "vue";
import * as echarts from "echarts";
import axios from "axios";
import { useOnWheelHook } from "../hook.js";

const { VITE_FANRUAN_BASE_URL } = import.meta.env;

const props = defineProps({
  timeType: {
    type: String,
    default: ""
  },
  queryParams: {
    type: Object,
    default: () => {}
  }
});

const chartType = ref("桑基图");
const isShowDetail = ref(false);
const sysId = ref("");

const templateName = computed(() => {
  switch (props.timeType) {
    case "Daily":
      return (
        encodeURIComponent(encodeURIComponent(isShowDetail.value ? "energyBalanceUseRationDaily" : "energyFlowEquilibriumElectricityDaily")) + ".frm"
      );
      break;
    case "Monthly":
      return (
        encodeURIComponent(encodeURIComponent(isShowDetail.value ? "energyBalanceUseRationMonthly" : "energyFlowEquilibriumElectricityMonthly")) +
        ".frm"
      );
      break;
    case "Yearly":
      return (
        encodeURIComponent(encodeURIComponent(isShowDetail.value ? "energyBalanceUseRationYearly" : "energyFlowEquilibriumElectricityYearly")) +
        ".frm"
      );
      break;
    default:
      return (
        encodeURIComponent(encodeURIComponent(isShowDetail.value ? "energyBalanceUseRationMonthly" : "energyFlowEquilibriumElectricityMonthly")) +
        ".frm"
      );
      break;
  }
});

onMounted(() => {
  getSankeyData();
  window.addEventListener("message", function (event) {
    let o = `${window.location.protocol}//${window.location.hostname}:8443`;
    if (event.origin !== o) return;
    let msg = event.data;
    let sysId = msg ? msg.split("#")[1].split("=")[1] : "";
    if (sysId) {
      sysId.value = sysId;
    }
  });
});

const changeChartType = val => {
  chartType.value = val;
  isShowDetail.value = false;
};

// 获取桑基图数据
const getSankeyData = () => {
  axios
    .get("/models/energyBalance_elec.json")
    .then(res => {
      const data = res.data;
      nextTick(() => {
        drawSankeyChart(data);
      });
    })
    .catch(error => {
      console.log(error);
    });
};

const sankeyChartDomRef = ref(null);
// 电 桑基图
const drawSankeyChart = data => {
  let myChart = echarts.init(sankeyChartDomRef.value);
  let option = {
    tooltip: {
      trigger: "item",
      triggerOn: "mousemove"
    },
    grid: {
      top: 10
    },
    dataZoom: [
      {
        // 设置滚动条的隐藏或显示
        show: true,
        // 设置类型
        type: "slider",
        // 设置背景颜色
        backgroundColor: "rgb(19, 63, 100)",
        // 设置选中范围的填充颜色
        fillerColor: "rgb(16, 171, 198)",
        // 设置边框颜色
        borderColor: "rgb(19, 63, 100)",
        // 是否显示detail，即拖拽时候显示详细数值信息
        showDetail: false,
        // 数据窗口范围的起始数值
        startValue: 0,
        // 数据窗口范围的结束数值（一页显示多少条数据）
        endValue: 5,
        // 控制哪个轴，如果是number表示控制一个轴，
        // 如果是Array表示控制多个轴。此处控制第二根轴
        yAxisIndex: [0, 1],
        // empty：当前数据窗口外的数据，被设置为空。
        // 即不会影响其他轴的数据范围
        filterMode: "empty",
        // 滚动条高度
        width: 8,
        // 滚动条显示位置
        height: "80%",
        // 距离右边
        right: 3,
        // 控制手柄的尺寸
        handleSize: 0,
        // 是否锁定选择区域（或叫做数据窗口）的大小
        zoomLoxk: true,
        // 组件离容器上侧的距离
        // 如果top的值为'top', 'middle', 'bottom'，组件会根据相应的位置自动对齐
        top: "middle"
      },
      {
        // 没有下面这块的话，只能拖动滚动条，
        // 鼠标滚轮在区域内不能控制外部滚动条
        type: "inside",
        // 控制哪个轴，如果是number表示控制一个轴，
        // 如果是Array表示控制多个轴。此处控制第二根轴
        yAxisIndex: [0, 1],
        // 滚轮是否触发缩放
        zoomOnMouseWheel: false,
        // 鼠标移动能否触发平移
        moveOnMouseMove: true,
        // 鼠标滚轮能否触发平移
        moveOnMouseWheel: true
      }
    ],
    series: [
      {
        type: "sankey",
        data: data.nodes,
        links: data.links,
        emphasis: {
          focus: "adjacency"
        },
        levels: [
          {
            depth: 0,
            itemStyle: {
              color: "#fbb4ae"
            },
            lineStyle: {
              color: "source",
              opacity: 0.6
            }
          },
          {
            depth: 1,
            itemStyle: {
              color: "#b3cde3"
            },
            lineStyle: {
              color: "source",
              opacity: 0.6
            }
          },
          {
            depth: 2,
            itemStyle: {
              color: "#ccebc5"
            },
            lineStyle: {
              color: "source",
              opacity: 0.6
            }
          },
          {
            depth: 3,
            itemStyle: {
              color: "#decbe4"
            },
            lineStyle: {
              color: "source",
              opacity: 0.6
            }
          },
          {
            depth: 4,
            itemStyle: {
              color: "#9E47C3"
            },
            lineStyle: {
              color: "source",
              opacity: 0.6
            }
          },
          {
            depth: 5,
            itemStyle: {
              color: "#F1647A"
            },
            lineStyle: {
              color: "source",
              opacity: 0.6
            }
          }
        ],
        lineStyle: {
          curveness: 0.5
        }
      }
    ]
  };
  option && myChart.setOption(option);
  myChart.on("click", function (params) {
    sysId.value = params.data.source ?? params.name;
    isShowDetail.value = true;
  });
};

const backClick = () => {
  isShowDetail.value = false;
};

// 滚动缩小
const { wheelScale, onWheel } = useOnWheelHook();
</script>

<style lang="scss" scoped>
@import url("@/views/common/energy/reused/flowEquilibrium/component/index.scss");

.sankey-chart {
  position: relative;
  top: 0;
  left: 0;
  width: 100%;
  height: 2500px;
  margin: 0 auto;
  transform-origin: 50% 0%;
}

.draggable {
  cursor: grab;
  user-select: none;
  transition: transform 0.2s ease; /* 添加平滑过渡效果 */
  will-change: transform; /* 优化性能 */
}

.draggable:active {
  cursor: grabbing;
}

.iframe-wrap {
  height: 100%;
  overflow: auto;
}
</style>
